package com.shizhanzhe.zxbapp.pay;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.zxbapp.R;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.bean.UserLM;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.zxbapp.utils.SharedPreferencesUtils;
import com.shizhanzhe.zxbapp.widget.WXQRPopupWindow;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import static com.shizhanzhe.zxbapp.bean.UserBean.uid;

/**
 * Created by zz9527 on 2018/10/30.
 * VIP购买
 */
public class PayVIPActivity extends Activity implements View.OnClickListener {
    private RadioButton zfb;
    private RadioButton wx;
    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        getLevel(UserBean.uid);
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PayVIPActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayVIPActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

                    }
                    break;

            }
        }
    };
    private TextView money;
    private String price;
    private IWXAPI mWXApi;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        ImmersionBar.with(this)
                .statusBarView(R.id.bar_0_view)
                .init();
        zfb = findViewById(R.id.zfb);
        wx = findViewById(R.id.wx);

        findViewById(R.id.ll_zfb).setOnClickListener(this);
        findViewById(R.id.ll_wx).setOnClickListener(this);
        findViewById(R.id.btn_pay).setOnClickListener(this);
        findViewById(R.id.backarea).setOnClickListener(this);
        money = findViewById(R.id.money);
        getVIPMoney();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_zfb:
                zfb.setChecked(true);
                break;
            case R.id.ll_wx:
                wx.setChecked(true);
                break;
            case R.id.btn_pay:
                if (zfb.isChecked()) {
                    getOrder();
                } else if (wx.isChecked()) {
                    mWXApi = WXAPIFactory.createWXAPI(this, null);
                    // 将该app注册到微信
                    mWXApi.registerApp("wx8ec35c73c8f4e83e");
                    if (!check()){
                        Toast.makeText(this, "未安装微信或微信版本过低", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    WXPay();
                }
                break;
            case R.id.backarea:
                finish();
                break;
        }
    }

    private void getOrder() {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.VIP(uid, price), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                rechargeZFB(json);
            }
        });
    }

    //支付宝支付
    private void rechargeZFB(final String orderInfo) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask payTask = new PayTask(PayVIPActivity.this);
                Map<String, String> result = payTask.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void getLevel(int uid) {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.money + "?uid=" + uid, new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    Gson gson = new Gson();
                    UserLM userLM = gson.fromJson(json, UserLM.class);
                    UserBean.level = userLM.getInfo().getLevel();
                    if (UserBean.level > 0) {
                        SharedPreferencesUtils.setParam(PayVIPActivity.this, "level", UserBean.level);
                        Toast.makeText(PayVIPActivity.this, "恭喜成为VIP", Toast.LENGTH_SHORT).show();
                        finish();
                    }else {
                        Toast.makeText(PayVIPActivity.this, "未开通VIP", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private void getVIPMoney() {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.VIPMONEY(), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        JSONObject object = new JSONObject(json);
                        price = object.optString("money");
                        money.setText("VIP\n¥" + object.optString("money"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void WXPay(){
        OkHttpDownloadJsonUtil.downloadJson(this, Path.VIPWX(UserBean.uid, price), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    JSONObject object = jsonObject.getJSONObject("response");
                    PayReq request = new PayReq();
                    request.appId = "wx8ec35c73c8f4e83e";
                    request.partnerId = "1519496201";
                    request.prepayId= object.optString("prepayid");
                    request.packageValue = "Sign=WXPay";
                    request.nonceStr=object.optString("noncestr");
                    request.timeStamp=object.optString("timestamp");
                    request.sign=object.optString("sign");
                    mWXApi.sendReq(request);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }
    //检测是否支持微信支付
    private boolean check() {
        return mWXApi.isWXAppInstalled() && mWXApi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy(); //必须调用该方法，防止内存泄漏
    }

    @Override
    protected void onResume() {
        super.onResume();
        getLevel(UserBean.uid);
    }
}
